/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
 *
 */

import { hvigorCore } from '@ohos/hvigor';

import { ProjectBuildProfile } from '../../options/build/project-build-profile.js';
import ProjectProfileOpt = ProjectBuildProfile.ProjectProfileOpt;
import { getElementFromArr } from '../../utils/array-util.js';
import ProductBuildOpt = ProjectBuildProfile.ProductBuildOpt;
import { projectBuildProfileLoader } from '../../utils/loader/file/project-build-profile-loader.js';

export class CoreProjectProfile {
  private profileOpt: ProjectProfileOpt | undefined;
  private readonly projectPath: string;
  private static coreProjectProfile: CoreProjectProfile;

  private constructor(projectPath: string) {
    this.projectPath = projectPath;

    this.loadProfile();
  }

  static getInstance(projectPath: string): CoreProjectProfile {
    this.coreProjectProfile = new CoreProjectProfile(projectPath);
    return this.coreProjectProfile;
  }

  private loadProfile(): void {
    this.profileOpt = projectBuildProfileLoader.getBuildProfile();
  }

  getProjectProfileOpt(): ProjectProfileOpt {
    // 需要每次刷新 因为可能上次同步和本次同步的时候用户修改了build-profile.json5
    this.loadProfile();
    return this.profileOpt!;
  }

  getCurrentProductOpt(): ProductBuildOpt {
    const configProduct = hvigorCore.getExtraConfig().get('product');
    const currentProduct = configProduct ?? 'default';
    return getElementFromArr(this.getProjectProfileOpt().app.products, currentProduct) as ProductBuildOpt;
  }
}
